<template>
  <div class="user-authority pad">
    <div class="head">
      <span>用户权限管理</span>
    </div>
    <el-tabs type="border-card" class="m-t-b" @tab-click="tabClick">
      <el-tab-pane label="权限管理">
        <div style="display: flex; justify-content: space-between;">
          <div>
            <el-input
              style="width: 260px;"
              placeholder="输入权限标题搜索"
              v-model="searchText"
              @input="clearSearch"
              clearable
              @keypress.native.enter="handleSearch"
            />
            <el-button
              type="primary"
              style="margin-left: 15px;"
              @click="handleSearch"
            >
              <i class="el-icon-search"></i>
              搜索
            </el-button>
          </div>
          <el-button type="primary" @click="openAddAuthorityDialog">
            <i class="el-icon-plus"></i>
            添加权限
          </el-button>
        </div>
        <el-table :data="authorityList" stripe border v-loading="authorityLoading" class="m-t-b">
          <el-table-column label="权限标题">
            <template slot-scope="scope">
              {{scope.row.userPermissionName ? scope.row.userPermissionName : '无'}}
            </template>
          </el-table-column>
          <el-table-column label="菜单图标">
            <template slot-scope="scope">
              {{scope.row.userPermissionIcon ? scope.row.userPermissionIcon : '无'}}
            </template>
          </el-table-column>
          <el-table-column label="菜单排序">
            <template slot-scope="scope">
              {{scope.row.userPermissionSort ? scope.row.userPermissionSort : '无'}}
            </template>
          </el-table-column>
          <el-table-column label="页面路径">
            <template slot-scope="scope">
              {{scope.row.userPermissionUrl ? scope.row.userPermissionUrl : '无'}}
            </template>
          </el-table-column>
          <el-table-column label="对应按钮控制value">
            <template slot-scope="scope">
              {{scope.row.userPermissionValue ? scope.row.userPermissionValue : '无'}}
            </template>
          </el-table-column>
          <el-table-column label="权限类型">
            <template slot-scope="scope">
              {{scope.row.userPermissionType | typeFilTer}}
            </template>
          </el-table-column>
          <el-table-column label="关联父级">
            <template slot-scope="scope">
              {{scope.row.parentName ? scope.row.parentName : '无'}}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createDate"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="default" circle icon="el-icon-edit" @click="openUpdateAuthorityDialog(scope.row)"></el-button>
              <el-button type="danger" circle icon="el-icon-delete" @click="confirmDelete(scope.row, '权限')"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleAuthorityPage"
          :current-page="curAuthPage"
          :total="authorityTotal">
        </el-pagination>

      </el-tab-pane>
      <el-tab-pane label="角色管理">
        <el-button type="primary" @click="openRoleAddDialog">
          <i class="el-icon-plus"></i>
          添加角色
        </el-button>
        <el-table :data="roleList" stripe border class="m-t-b" v-loading="roleLoading">
          <el-table-column label="角色名称" prop="userRoleTitle"></el-table-column>
          <el-table-column label="角色描述" prop="userRoleDetail">
            <template slot-scope="scope">
              {{scope.row.userRoleDetail ? scope.row.userRoleDetail : '暂无'}}
            </template>
          </el-table-column>
          <el-table-column label="上级角色">
            <template slot-scope="scope">
              <!-- {{scope.row.parentId ? scope.row.parentId : '无'}} -->
              {{scope.row.parentName}}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="default"
                circle
                icon="el-icon-edit"
                @click="openRoleUpdateDialog(scope.row)"
                v-if="(scope.row.userRoleTitle !== '学校') && (scope.row.userRoleTitle !== '公司')"
              ></el-button>
              <el-button
                type="info"
                circle
                icon="el-icon-setting"
                @click="openSetAuthDialog(scope.row)"
              ></el-button>
              <el-button
                type="danger"
                disabled
                circle
                icon="el-icon-delete"
                v-if="(scope.row.userRoleTitle !== '学校') && (scope.row.userRoleTitle !== '公司')"
                @click="confirmDelete(scope.row, '角色')"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex m-t-b"
          :page-size="pageSize"
          layout="prev, pager, next"
          @current-change="handleRolePage"
          :total="roleTotal">
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="authorityDialogTitle" :visible.sync="showAuthorityDialog">
      <el-form :model="authority" label-position="top" ref="authority" :rules="rules">
        <el-form-item label="权限类型" prop="userPermissionType">
          <el-select v-model="authority.userPermissionType" @change="changeAuthType">
            <el-option :value="0" label="主菜单"></el-option>
            <el-option :value="1" label="子菜单"></el-option>
            <el-option :value="2" label="功能"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限标题" prop="userPermissionName">
          <el-input v-model="authority.userPermissionName" />
        </el-form-item>
        <el-form-item label="页面路径" v-if="authority.userPermissionType === 1">
          <el-input v-model="authority.userPermissionUrl" />
        </el-form-item>
        <el-form-item label="对应按钮控制value" v-if="authority.userPermissionType === 2">
          <el-input v-model="authority.userPermissionValue" />
        </el-form-item>
        <el-form-item label="权限排序" v-if="authority.userPermissionType !== 2">
          <el-input
            type="number"
            placeholder="设置左侧菜单项先后顺序(数字越小越靠前)"
            v-model="authority.userPermissionSort"
          />
        </el-form-item>
        <el-form-item label="菜单图标" v-if="authority.userPermissionType === 0">
          <el-input v-model="authority.userPermissionIcon" />
        </el-form-item>
        <el-form-item label="关联父级" v-if="authority.userPermissionType != 0">
          <el-select filterable v-model="authority.parentId">
            <el-option
              v-for="(item, i) in fitAuthorityList"
              :key="i"
              :value="item.userPermissionId"
              :label="item.userPermissionName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideAuthorityDialog">取 消</el-button>
        <el-button type="primary" @click="fetchAddAuthority('authority')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="roleDialogTitle" :visible.sync="showRoleDialog">
      <el-form :model="role" ref="role" :rules="rules" label-position="top">
        <el-form-item label="角色名称" prop="userRoleTitle">
          <el-input v-model="role.userRoleTitle" />
        </el-form-item>
        <el-form-item label="角色描述" prop="userRoleDetail">
          <el-input v-model="role.userRoleDetail" />
        </el-form-item>
        <el-form-item label="上级角色" prop="parentId">
          <el-select v-model="role.parentId">
            <el-option
              v-for="(role, i) in allRoleList"
              :key="i"
              :value="role.userRoleId"
              :label="role.userRoleTitle"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideRoleDialog">取 消</el-button>
        <el-button type="primary" @click="fetchAddRole('role')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addAuthority,
  updateAuthority,
  deleteAuthority,
  getAuthorityByPage,
  addRole,
  updateRole,
  deleteRole,
  getRoleListByPage,
  getAuthorityByType,
  getAllRoleList
} from '../api';
import { formatDate } from '../util';

export default {
  name: 'UserAuthority',
  data () {
    const validateParentRole = (rules, value, callback) => {
      if (value) {
        let title = this.allRoleList.filter(item => item.userRoleId === value)[0].userRoleTitle;
        if (title === this.role.userRoleTitle) {
          callback(new Error('所选上级角色名称不能与新建角色名称相同'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    };
    return {
      authorityDialogTitle: '添加权限',
      showAuthorityDialog: false,
      authorityLoading: false,
      curAuthPage: 1,
      roleLoading: false,
      pageSize: 10,
      authorityTotal: 0,
      authorityList: [],
      fitAuthorityList: [],
      searchText: '',
      authority: { // 权限
        userPermissionName: '',
        userPermissionIcon: '',
        userPermissionType: '',
        parentId: '',
        userPermissionLevel: '',
        userPermissionValue: '',
        userPermissionUrl: '',
        userPermissionSort: ''
      },
      roleDialogTitle: '添加角色',
      showRoleDialog: false,
      role: {
        userRoleTitle: '',
        parentId: '',
        userRoleDetail: ''
      },
      allRoleList: [],
      roleList: [],
      roleTotal: 0,
      roleAuthList: [],
      roleAuthTotal: 0,
      roleAuthLoading: false,
      rules: {
        userPermissionName: [
          { required: true, message: '权限标题不能为空', trigger: 'blur' }
        ],
        userPermissionType: [
          { required: true, message: '权限类型不能为空', trigger: 'blur' }
        ],
        userPermissionValue: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' }
        ],
        userRoleTitle: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        parentId: [
          { validator: validateParentRole, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    tabClick ({ index }) { // tab页点击事件
      if (index == 1 && !this.roleList.length) {
        this.fetchRoleList(1)
      } else if (index == 2) {

      }
    },
    clearSearch () { // 清除搜索
      if (!this.searchText.trim()) {
        this.fetchAuthorityByPage(1)
      }
    },
    handleSearch () { // 搜索
      if (!this.searchText.trim()) {
        return this.$message.error('请输入有效搜索内容')
      };
      this.fetchAuthorityByPage(1)
    },
    openAddAuthorityDialog () { // 打开添加权限对话框
      if (!this.$checkAuth('canAddAuthority')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.authority.userPermissionName = '';
      this.authority.userPermissionUrl = '';
      this.authority.userPermissionType = '';
      this.authority.userPermissionIcon = '';
      this.authority.userPermissionSort = '';
      this.authority.userPermissionValue = '';
      this.authority.parentId = '';
      this.authorityDialogTitle = '添加权限';
      this.showAuthorityDialog = true
    },
    hideAuthorityDialog () { // 隐藏权限弹出框
      this.showAuthorityDialog = false
    },
    fetchAddAuthority (name) { // 添加权限
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.authorityDialogTitle === '添加权限') {
            addAuthority({
              userPermissionType: this.authority.userPermissionType,
              userPermissionName: this.authority.userPermissionName,
              userPermissionUrl: this.authority.userPermissionUrl,
              userPermissionSort: this.authority.userPermissionSort || null,
              userPermissionIcon: this.authority.userPermissionIcon || null,
              userPermissionValue: this.authority.userPermissionValue || null,
              parentId: this.authority.parentId || null
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                });
                this.showAuthorityDialog = false;
                this.fetchAuthorityByPage(this.curAuthPage)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              }
            })
            .catch(e => {
              this.$message.error('服务异常!')
            })
          } else {
            updateAuthority({
              userPermissionId: this.authority.authorityId,
              userPermissionType: this.authority.userPermissionType,
              userPermissionName: this.authority.userPermissionName,
              userPermissionUrl: this.authority.userPermissionUrl,
              userPermissionIcon: this.authority.userPermissionIcon || null,
              userPermissionSort: this.authority.userPermissionSort || null,
              userPermissionValue: this.authority.userPermissionValue || null,
              parentId: this.authority.parentId || null
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                });
                this.showAuthorityDialog = false;
                this.fetchAuthorityByPage(this.curAuthPage)
              } else {
                this.$message.error(res.data.msg || '服务异常！')
              }
            })
            .catch(e => {
              this.$message.error('服务异常！')
            })
          }
        } else {
          return false
        }
      })
    },
    fetchAuthorityByPage (index) { // 分页查询权限列表
      this.authorityLoading = true;
      getAuthorityByPage({
        count: this.pageSize,
        index,
        queryParam: {
          userPermissionName: this.searchText || null
        }
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          list.forEach(item => {
            item.createDate = formatDate(item.createDate)
          });
          this.authorityTotal = res.data.data.totalRecord;
          this.authorityList = list
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        };
        this.authorityLoading = false
      })
      .catch(e => {
        this.authorityLoading = false;
        this.$message.error('服务异常!')
      })
    },
    handleAuthorityPage (page) { // 权限列表分页事件
      this.curAuthPage = page;
      this.fetchAuthorityByPage(page)
    },
    openUpdateAuthorityDialog (data) { // 打开更新权限弹出框
      if (!this.$checkAuth('canEditAuthority')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.authority.userPermissionName = data.userPermissionName;
      this.authority.userPermissionUrl = data.userPermissionUrl;
      this.authority.userPermissionType = Number(data.userPermissionType);
      this.authority.userPermissionIcon = data.userPermissionIcon;
      this.authority.userPermissionSort = data.userPermissionSort;
      this.authority.userPermissionValue = data.userPermissionValue;
      this.authority.parentId = Number(data.parentId);
      this.authority.authorityId = data.userPermissionId;
      this.authorityDialogTitle = '修改权限';
      this.showAuthorityDialog = true
    },
    fetchDeleteAuthority (userPermissionId) { // 删除权限
      deleteAuthority(userPermissionId)
      .then(res => {
        if (res.data.code === 1) {
          this.$message({
            type: 'success',
            message: '删除成功'
          });
          this.fetchAuthorityByPage(1)
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    confirmDelete (data, type) { // 确认删除
      this.$confirm(`确定删除此${type}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        if (type === '权限') {
          if (!this.$checkAuth('canDeleteAuthority')) {
            return this.$message.error('暂无对应操作权限!')
          };
          this.fetchDeleteAuthority(data.userPermissionId)
        } else if (type === '角色') {
          if (!this.$checkAuth('canDeleteRole')) {
            return this.$message.error('暂无对应操作权限!')
          };
          this.fetchDeleteRole(data.userRoleId)
        }
      })
      .catch(e => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },
    openRoleAddDialog () { // 打开添加角色弹出框
      if (!this.$checkAuth('canAddRole')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.role.userRoleTitle = '';
      this.role.userRoleDetail = '';
      this.role.parentId = '';
      this.roleDialogTitle = '添加角色';
      this.showRoleDialog = true
    },
    hideRoleDialog () { // 隐藏角色弹出框
      this.showRoleDialog = false
    },
    fetchAddRole (name) { // 添加角色
      this.$refs[name].validate(valid => {
        if (valid) {
          if (this.roleDialogTitle === '添加角色') {
            addRole({
              userRoleTitle: this.role.userRoleTitle,
              parentId: this.role.parentId || null,
              userRoleDetail: this.role.userRoleDetail || null
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                });
                this.showRoleDialog = false;
                this.fetchRoleList(1);
                this.fetchAllRoleList()
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              }
            })
            .catch(e => {
              this.$message.error('服务异常!')
            })
          } else {
            updateRole({
              userRoleId: this.role.userRoleId,
              userRoleTitle: this.role.userRoleTitle,
              parentId: this.role.parentId || null,
              userRoleDetail: this.role.userRoleDetail || null
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                });
                this.showRoleDialog = false;
                this.fetchRoleList(1);
                this.fetchAllRoleList()
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              }
            })
            .catch(e => {
              this.$message.error('服务异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    fetchRoleList (index) { // 获取角色列表
      this.roleLoading = true;
      getRoleListByPage({
        count: this.pageSize,
        index
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          this.roleTotal = res.data.data.totalRecord;
          list.forEach(item => {
            item.createDate = formatDate(item.createDate);
            // item.parentName = item.parentId ? this.allRoleList.filter(role => role.userRoleId == item.parentId)[0].userRoleTitle : '无'
            item.parentName = item.parentId || '暂无'
          });
          this.roleList = list
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        };
        this.roleLoading = false
      })
      .catch(e => {
        console.log(e)
        this.roleLoading = false;
        this.$message.error('服务异常!')
      })
    },
    handleRolePage (page) { // 角色分页事件
      this.fetchRoleList(page)
    },
    openRoleUpdateDialog (data) { // 打开角色更新弹出框
      if (!this.$checkAuth('canEditRole')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.role.userRoleId = data.userRoleId;
      this.role.userRoleTitle = data.userRoleTitle;
      this.role.userRoleDetail = data.userRoleDetail;
      this.role.parentId = data.parentId;
      this.roleDialogTitle = '修改角色';
      this.showRoleDialog = true
    },
    fetchDeleteRole (userRoleId) { // 删除角色
      deleteRole(userRoleId)
      .then(res => {
        if (res.data.code === 1) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.fetchRoleList(1)
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    openSetAuthDialog (data) { // 打开设置权限弹出框
      if (!this.$checkAuth('canSetAuthorityForRole')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.$router.push(`/user/authority/set/${data.userRoleId}`)
    },
    fetchAuthorityByType (type) { // 根据类型查询权限
      getAuthorityByType(type)
      .then(res => {
        if (res.data.code === 1) {
          this.fitAuthorityList = res.data.data || []
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    changeAuthType (e) { // 权限类型改变
      if (e === 1) {
        this.fetchAuthorityByType(0)
      } else if (e === 2) {
        this.fetchAuthorityByType(1)
      }
    },
    fetchAllRoleList () { // 不分页查询所有角色
      getAllRoleList()
      .then(res => {
        if (res.data.code === 1) {
          this.allRoleList = res.data.data || [];
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    }
  },
  created () {
    this.fetchAuthorityByPage(1);
    this.fetchAllRoleList()
  },
  filters: {
    typeFilTer (type) {
      let res = '';
      type = Number(type);
      switch (type) {
        case 0:
          res = '主菜单';
          break
        case 1:
          res = '子菜单';
          break
        case 2:
          res = '功能';
          break
        default:
          break
      };
      return res
    }
  }
}
</script>
<style lang="scss">
  .user-authority {
    
  }
</style>
